<template>
  <div id="discount_coupon_list">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex" justify="start" class="search-item-left">
          <Col class="search-item"><span class="search-label">优惠券名称：</span><Input placeholder="请输入" :maxlength="20" v-model='couponName' @on-keyup='filterSpace' @on-blur="filterSpace"></Input></Col>
          <Col class="search-item">
            <span class="search-label">状态：</span>
            <Select v-model="searchObj.status" @on-change="search" style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="item in couponStatusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">类型：</span>
            <Select v-model="searchObj.couponType" @on-change="search" style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="item in couponTypeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" type='primary' @click="doSearch">查询</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex" justify="end" class="search-item-right">
          <Col class="search-item"><Button class="search-btn" type="primary" style="margin-right:8px" @click="skipAdd">添加</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe class="table-list" :columns="columns" :data="data" :loading="loading" :height="this.tableHeight">
      <template slot-scope="{ row }" slot="couponCode">
         {{ row.couponBase.couponCode }}
      </template>
      <template slot-scope="{ row }" slot="couponName">
         {{ row.couponBase.couponName }}
      </template>
      <template slot-scope="{ row }" slot="couponType">
         {{ getEnumsName(row.couponBase.couponType, couponTypeList) }}
      </template>
      <template slot-scope="{ row }" slot="applyProduct">
         {{ row.rules[0].matchRules.itemId | getCategorysName }}
      </template>
      <template slot-scope="{ row }" slot="validTime">
         {{ row.couponBase.expirationType ? (row.couponBase.startTime + '至' + row.couponBase.endTime) : (row.couponBase.dayNum + '天') }}
      </template>
      <template slot-scope="{ row }" slot="status">
         {{ getEnumsName(row.couponBase.status, couponStatusList) }}
      </template>
      <template slot-scope="{ row }" slot="creatorName">
         {{ row.couponBase.creatorName }}
      </template>
      <template slot-scope="{ row }" slot="createTime">
         {{ row.couponBase.createTime }}
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys icondetail" title="查看详情" @click="skipDetail(row)" v-if="hasPermission('moms:market:coupondetail')"></i>
        <i class="iconsys iconedit" title="编辑" @click="skipEdit(row)" v-if="hasPermission('moms:market:couponupdate') && row.couponBase.status === 0"></i>
        <Poptip confirm title="你确定要删除吗？"  transfer @on-ok="sureDel(row)">
          <i class="iconsys icondel" title="删除" v-if="hasPermission('moms:market:coupondelete')  && row.couponBase.status === 0"></i>
        </Poptip>
        <Poptip confirm :title="'你确定要启用吗？'" transfer @on-ok="doStatus(row, 1)">
          <i class="iconsys iconshangjia" title="启用" v-if="hasPermission('moms:market:couponstatusupdate') && row.couponBase.status === 0"></i>
        </Poptip>
        <Poptip confirm :title="'你确定要停用吗？'" transfer @on-ok="doStatus(row, 2)">
          <i class="iconsys iconxiajia" title="停用" v-if="hasPermission('moms:market:couponstatusupdate') && row.couponBase.status === 1"></i>
        </Poptip>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
       <Page :total="total"
              :page-size='pageSize'
              :current='pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getCouponLists, delCoupon, doCouponStatus } from '@/api/market/coupon.js'
import enumsMixin from '../enums.js'
let that
export default {
  name: 'market_coupon_list',
  mixins: [enumsMixin],
  data () {
    return {
      couponName: '',
      searchObj: {
        couponName: '',
        status: -1,
        couponType: -1
      },
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      loading: false,
      tableHeight: 0,
      data: [],
      columns: [
        {
          title: '编号',
          slot: 'couponCode'
        },
        {
          title: '名称',
          slot: 'couponName'
        },
        {
          title: '类型',
          slot: 'couponType'
        },
        {
          title: '适用产品',
          slot: 'applyProduct'
        },
        {
          title: '有效期',
          slot: 'validTime'
        },
        {
          title: '状态',
          slot: 'status'
        },
        {
          title: '创建人',
          slot: 'creatorName'
        },
        {
          title: '创建时间',
          slot: 'createTime'
        }
      ]
    }
  },
  beforeCreate: function () {
    that = this
  },
  filters: {
    getCategorysName (value) {
      if (Array.isArray(value)) {
        return value.map((value) => {
          const result = that.categoryList.filter(item => +item['value'] === +value)
          return result[0] ? result[0]['label'] : ''
        }).join('/')
      }
      return ''
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'market_coupon_list') {
        this.getData()
      }
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  mounted () {
    this.getData()
    if (this.hasPermission(['moms:market:couponupdate', 'moms:market:coupondelete', 'moms:market:coupondetail', 'moms:market:couponstatusupdate'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 200
      })
    }
  },
  methods: {
    filterSpace () {
      this.couponName = this.couponName.replace(/\s+/g, '')
    },
    getData () {
      this.loading = true
      this.tableHeight = 0
      let params = {
        merchantId: this.merchantId,
        couponName: this.searchObj.couponName,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize
      }
      if (this.searchObj.status !== -1) {
        params.status = this.searchObj.status
      }
      if (this.searchObj.couponType !== -1) {
        params.couponType = this.searchObj.couponType
      }
      getCouponLists(params).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.data = result.data || []
          this.total = result.totalCount || 0
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    doSearch () {
      this.searchObj.couponName = this.couponName
      this.search()
    },
    reset () {
      this.couponName = ''
      this.searchObj = {
        couponName: '',
        status: -1,
        couponType: -1
      }
      this.search()
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    skipAdd () {
      this.$router.push({ name: 'market_coupon_create' })
    },
    skipEdit (row) {
      this.$router.push({ name: 'market_coupon_edit', params: { id: row.couponBase.couponId } })
    },
    skipDetail (row) {
      this.$router.push({ name: 'market_coupon_detail', params: { id: row.couponBase.couponId } })
    },
    sureDel (row) {
      delCoupon({
        merchantId: this.merchantId,
        couponId: row.couponBase.couponId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          setTimeout(() => {
            this.getData()
          }, 300)
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    doStatus (row, type) {
      doCouponStatus({
        merchantId: this.merchantId,
        itemId: row.couponBase.couponId,
        status: type,
        modifierId: this.userId,
        modifierName: this.userName
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success((type === 1 ? '启用' : '停用') + '成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    }
  }
}
</script>
